#include "KRuntime.h"
#include "KIniFile.h"

namespace krt
{
	CustomIniFile::CustomIniFile()
	{
	}

	CustomIniFile::~CustomIniFile()
	{
	}

	SimpleIniFile::SimpleIniFile(const TCHAR *FileName):CustomIniFile()
	{
		_tcscpy_s(m_FileName, MAX_PATH, FileName);
	}

	SimpleIniFile::~SimpleIniFile()
	{
		CustomIniFile::~CustomIniFile();
	}

	BOOL SimpleIniFile::SectionExists(const TCHAR* section)
	{
		if (!section)
			return FALSE;

		size_t len = _tcslen(section);

		if (len == 0)
			return FALSE;

		TCHAR namelist[4096];

		size_t total = ::GetPrivateProfileSectionNames(
			namelist, 
			sizeof(namelist)/sizeof(namelist[0]), 
			m_FileName);

		if (total == 0)
			return FALSE;	

		BOOL flag = TRUE;
		size_t j = 0;

		for(size_t i = 0; i < total; ++i)
		{
			TCHAR c1, c2;

			if (section[j] >= _T('a') && section[j] <= _T('z'))
				c1 = section[j] & ~32;
			else
				c1 = section[j];

			if (namelist[i] >= _T('a') && namelist[i] <= _T('z'))
				c2 = namelist[i] & ~32;
			else
				c2 = namelist[i];

			if (flag)
			{
				if (c1 == c2)
				{
					if (j == len)
						return TRUE;
					else j++;
				}
				else if (0 == c2)
				{
					flag = TRUE;
					j = 0;
				}
				else
					flag = FALSE;
			}
			else if (0 == c2)
			{
				flag = TRUE;
				j = 0;
			}	
		}

		return FALSE;
	}

	BOOL SimpleIniFile::KeyExists(
		const TCHAR* SectionName,
		const TCHAR* KeyName)
	{
		return TRUE;
	}

	int SimpleIniFile::ReadInteger(
		const TCHAR* section,
		const TCHAR* key,
		int _default) 
	{
		return ::GetPrivateProfileInt(section, key, _default, m_FileName);
	}

	TCHAR* SimpleIniFile::ReadString(
		const TCHAR* section,
		const TCHAR* key,
		const TCHAR* _default,
		TCHAR *buf,
		size_t len)
	{
		if (!::GetPrivateProfileString(section, key, _default, buf, len, m_FileName))
			buf[0] = 0;

		return buf;
	}

	double SimpleIniFile::ReadFloat(
		const TCHAR* section,
		const TCHAR* key,
		double _default)
	{
		TCHAR value[64];

		if (ReadString(section, key, NULL, value, sizeof(value)/sizeof(value[0])))
		{
			TCHAR *endptr = NULL;
			return _tcstod(value, &endptr);
		}
		else
			return _default;
	}

}